<?php

namespace app\admin\controller\classroom;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use think\response\Json;

/**
 * 试卷
 *
 * @icon fa fa-circle-o
 */
class Test extends Backend
{

    /**
     * Test模型对象
     * @var \app\admin\model\classroom\Test
     */
    protected $model = null;
    protected $type_arr = ['1'=>'选择题','2'=>'多选题','3'=>'判断题','4'=>'填空题','5'=>'问答题'];
    protected $multiFields = "status,retake";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\classroom\Test;
        $this->view->assign("statusList", $this->model->getStatusList());
        if(in_array($this->request->action(),['add','edit'])){
            $type_arr = [];
            foreach ($this->type_arr as $k=>$v) {
                $type_arr[] = ['id'=>$k,'value'=>$v];
            }
            $this->view->assign("type_arr", json_encode($type_arr,256));
        }
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as $row) {
            $row->countQuestion = Db::name('classroom_question')->where('test_id',$row->id)->count();
            $row->countTestLog = Db::name('classroom_test_log')->where('test_id',$row->id)->count();
            $row->countAssign = Db::name('classroom_test_assign')->where('test_id',$row->id)->count();
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $params['score_config'] = json_encode($params['score_config'],256);

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $row['score_config'] = json_decode($row['score_config'],true);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['score_config'] = json_encode($params['score_config'],256);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 详情
     */
    public function show($ids = null)
    {
        $row = $this->model->alias('a')->join('classroom_course b','a.course_id = b.id','LEFT')->field('a.*,b.name as course_name')
            ->where('a.id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $score_config = json_decode($row['score_config'],true);
        $score_config_arr = [];
        $type_arr = $this->type_arr;
        foreach ($score_config as $k=>$v) {
            $score_config_arr[$type_arr[$k]] = $v;
        }
        $this->view->assign('score_config_arr', $score_config_arr);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 题目编辑
     */
    public function question_list($ids = null)
    {
        $row = Db::name('classroom_test')->alias('a')->join('classroom_course b',"a.course_id = b.id","LEFT")
            ->field("a.*,b.name as course_name")
            ->where("a.id",$ids)
            ->find();
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 指定考试人员
     */
    public function user_assign($ids = null)
    {
        $test_row = Db::name("classroom_test")->where("id",$ids)->find();
        if (!$test_row) {
            $this->error(__('No Results were found'));
        }
        if($this->request->isPost()){
            $actions = $this->request->post("actions");
            if($actions === "set_group"){
                $group_id = $this->request->post("group_id/a");
                if(empty($group_id)) {
                    $this->error("未找到分组");
                }
                $u_ids = Db::name("user")->whereIn("group_id",$group_id)->where("status","normal")->column("id");
                if(!$u_ids){
                    $this->error("该分组没有用户");
                }
                $test_status_arr = Db::name("classroom_test_log")->field("*,MAX(is_pass) AS max_is_pass")->where("test_id",$ids)->where("status",1)->whereIn("user_id",$u_ids)->group("user_id")->order("id","desc")->select();
                $test_status_arr = array_column($test_status_arr,"max_is_pass","user_id");
                $insert = [];
                foreach ($u_ids as $k=>$v) {
                    $tmp['course_id'] = $test_row['course_id'];
                    $tmp['user_id'] = $v;
                    $tmp['test_id'] = $ids;
                    $tmp['status'] = isset($test_status_arr[$v]) ? $test_status_arr[$v] == 0 ? '未及格' : '完成' : '待完成';
                    $insert[] = $tmp;
                }
                Db::name("classroom_test_assign")->where("test_id",$ids)->delete();
                $result = Db::name("classroom_test_assign")->insertAll($insert);
                if($result !== false){
                    $this->success('设置分组用户成功');
                }
                $this->error("设置分组用户失败");
            } else if ($actions === "truncate"){
                $result = Db::name("classroom_test_assign")->where("test_id",$ids)->delete();
                if($result !== false){
                    $this->success('清空成功');
                }
                $this->error("清空失败");
            } else {
                $params = $this->request->post("row/a");
                Db::name("classroom_test_assign")->where("test_id",$ids)->delete();
                $insert = [];
                if(!empty($params['user'])){
                    $test_status_arr = Db::name("classroom_test_log")->field("*,MAX(is_pass) AS max_is_pass")->where("test_id",$ids)->where("status",1)->whereIn("user_id",$params['user'])->group("user_id")->order("id","desc")->select();
                    $test_status_arr = array_column($test_status_arr,"max_is_pass","user_id");
                    foreach ($params['user'] as $v) {
                        $tmp['course_id'] = $test_row['course_id'];
                        $tmp['user_id'] = $v;
                        $tmp['test_id'] = $ids;
                        $tmp['status'] = isset($test_status_arr[$v]) ? $test_status_arr[$v] == 0 ? '未及格' : '完成' : '待完成';
                        $insert[] = $tmp;
                    }
                }
                $result = Db::name("classroom_test_assign")->insertAll($insert);
                if($result !== false){
                    $this->success('设置分组用户成功');
                }
                $this->error("设置分组用户失败");
            }
        }

        $user_all = Db::name("user")->field("id,group_id,nickname")->where("status","normal")->select();
        $this->assign("user_all",$user_all);

        $users = Db::name("classroom_test_assign")->where("test_id",$ids)->column("user_id");
        $this->assign("users",$users);

        $user_group = Db::name("user_group")->field("id,name")->where("status","normal")->select();
        $this->assign("user_group",$user_group);

        $user_assign = Db::name("classroom_test_assign")->alias("a")->field("b.nickname,a.status")->join("user b","a.user_id = b.id","LEFT")->order("status","desc")->select();
        $this->assignconfig('user_assign',$user_assign);
        // $this->assign("user_assign",$user_assign);

        $this->assign("test_row",$test_row);
        return $this->view->fetch();
    }


}














